<?php

namespace app\controller;


use app\BaseController;
use app\model\UserRole;
use app\traits\CommonTrait;
use app\validate\PhoneCheck;
use app\validate\PwdForget;
use app\validate\Register;
use think\exception\ValidateException;
use think\facade\Cookie;
use think\facade\Db;
use think\facade\Log;
use think\facade\Request;
use app\model\User;
use think\facade\Session;

class AdminAuth extends BaseController
{
    use CommonTrait;

    public function login()
    {
        $phone = Request::post('phone');
        $password = Request::post('password');
        try {
            validate(PhoneCheck::class)->check([
                'phone' => $phone,
                'type' => 2
            ]);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->apiJson(-1, $e->getMessage());
        }
        $user = User::where(['phone' => $phone])->field('id,wx_unid,name,phone,douyin,token,password,salt,status')->findOrEmpty();
        if ($user->isEmpty()) {
            return $this->apiJson(-1, '手机号或密码不正确');
        }
        if ($user['status'] == 2) {
            return $this->apiJson(-1, '用户已被禁用');
        }
        if (password($password, $user['salt']) != $user['password']) {
            return $this->apiJson(-1, '手机号或密码不正确');
        }
        Session::set('uid', $user['id']);
        $roles = UserRole::where(['uid'=>$user['id']])->select();
        $token = generate_token($user,$roles);

      //  Cookie::set('token',$token);
        return $this->apiJson(1, '登录成功', ['token' =>$token]);
    }

    public function register()
    {
        $code = Request::post('code');
        $inviteCode = Request::post('invite_code');
        $password = Request::post('password');
        if (!$code && $code != '0') {
            return $this->apiJson(-1, '请输入验证码');
        }
        $regData = [
            'phone' => Request::post('phone'),
            'name' => Request::post('name'),
            'password' => $password,
            'invite_code' => $inviteCode
        ];
        try {
            validate(Register::class)->check($regData);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->apiJson(-1, $e->getMessage());
        }
        $verify = $this->verify(1, Request::post('phone'), $code);
        if (!$verify) {
            return $this->apiJson(-1, '验证码不正确');
        }
        $inviteUser = User::where(['invite_code' => $inviteCode, 'status' => 1])
            ->field('id,company_id,team_id')->findOrEmpty();
        if ($inviteUser->isEmpty()) {
            return $this->apiJson(-1, '邀请码不存在');
        }
        $salt = generate_salt();
        $regData['password'] = password($password, $salt);
        $regData['salt'] = $salt;
        $regData['invite_uid'] = $inviteUser['id'];
        $regData['invite_code'] = $this->generateInviteCode();
        $regData['company_id'] = $inviteUser['company_id'];
        $regData['team_id'] = $inviteUser['team_id'];
        $regData['head_img'] = 'http://douwuku.qilacps.com/api/images/default_head.png';
        $regData['is_system'] = 1;
        Db::startTrans();
        try {
            $uid = User::create($regData)->getLastInsID();
            UserRole::create(['uid' => $uid, 'rid' => 3]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            Log::info('创建用户失败' . $e->getMessage());
            return $this->apiJson(-1, '创建用户失败');
        }
        return $this->apiJson(1, 'success');
    }

    public function verify($type, $phone, $code)
    {
        $key = $phone . '_' . $type;

        $cache_code = cache_get($key);

        if (!$cache_code || ($code != $cache_code)) {
            return false;
        }
        return true;
    }

    //忘记密码
    public function pwdForget()
    {
        $phone = Request::post('phone');
        $password = Request::post('password');
        $code = Request::post('code');
        $forgetData = [
            'phone' => Request::post('phone'),
            'password' => $password,
            'code' => $code
        ];
        try {
            validate(PwdForget::class)->check($forgetData);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->apiJson(-1, $e->getMessage());
        }
        $user = User::where(['phone' => $phone])->field('salt')->findOrEmpty();
        if ($user->isEmpty()) {
            return $this->apiJson(-1, '账号不存在');
        }
        $verify = $this->verify(2, $phone, $code);
        if (!$verify) {
            return $this->apiJson(-1, '验证码不正确');
        }
        $newPwd = password($password, $user['salt']);
        User::where(['phone' => $phone])->update(['password' => $newPwd]);
        return $this->apiJson(1, 'success');
    }

    //退出
    public function logout()
    {
        $uid = Session::get('uid');
        if (!$uid) {
            return $this->apiJson(401, '你未登录');
        }
        Session::set('uid', null);
        return $this->apiJson(1, '退出成功');
    }

}